//缓存管理类

import 'package:shared_preferences/shared_preferences.dart';

class HiCache {
  late final SharedPreferences prefs;

  // 私有构造函数
  HiCache._();

  static HiCache? _instance;

  // 预初始化方法（异步）
  static Future<HiCache> preInit() async {
    if (_instance == null) {
      print("object初始化");
      final prefs = await SharedPreferences.getInstance();
      _instance = HiCache._();
      _instance!.prefs = prefs;
    }
    return _instance!;
  }

  // 获取实例（同步）
  static HiCache getInstance() {
    if (_instance == null) {
      throw Exception('HiCache not initialized. Call preInit() first.');
    }
    return _instance!;
  }

  // 便捷的实例获取方法，如果未初始化则自动初始化
  static Future<HiCache> get instance async {
    if (_instance == null) {
      return await preInit();
    }
    return _instance!;
  }

  // 数据存取方法
  Future<bool> setString(String key, String value) =>
      prefs.setString(key, value);
  Future<bool> setInt(String key, int value) => prefs.setInt(key, value);
  Future<bool> setDouble(String key, double value) =>
      prefs.setDouble(key, value);
  Future<bool> setBool(String key, bool value) => prefs.setBool(key, value);
  Future<bool> setStringList(String key, List<String> value) =>
      prefs.setStringList(key, value);

  String? getString(String key) => prefs.getString(key);
  int? getInt(String key) => prefs.getInt(key);
  double? getDouble(String key) => prefs.getDouble(key);
  bool? getBool(String key) => prefs.getBool(key);
  List<String>? getStringList(String key) => prefs.getStringList(key);

  Future<bool> remove(String key) => prefs.remove(key);
  Future<bool> clear() => prefs.clear();

  bool containsKey(String key) => prefs.containsKey(key);
  Set<String> getKeys() => prefs.getKeys();
}
